<template>
  <el-form ref="ruleForm" :model="formData" class="flexForm" label-position="top">
    <ContentAttachment ref="attachment" :dialog-show.sync="dialogShow" :attachment-type="attachmentType"
      @func="getData" />
    <div v-for="(formobj, index) in formObj" v-show="!formobj.notShow" :key="index" class="form-item">
      <el-form-item :label="formobj.label" :prop="formobj.prop" :rules="formobj.rules">
        <!-- inupt输入框 -->
        <el-input v-if="formobj.input" v-model="formData[formobj.prop]" size="small" :placeholder="formobj.placeholder"
          @input="inputINPUT($event, index, formobj.prop)" @change="inputChange($event, index, formobj.prop)" />
        <!-- textarea输入框 -->
        <el-input v-if="formobj.textarea" v-model="formData[formobj.prop]" size="small" type="textarea"
          :placeholder="formobj.placeholder" />
        <!-- 关联字段单选 -->
        <!-- {{ formobj }} -->
        <el-select v-if="formobj.reference" v-model="formData[formobj.prop]" filterable size="small"
          :placeholder="formobj.placeholder" :multiple="formobj.multiple"
          @change="selectChange($event, index, formobj.prop)">
          <el-option v-for="(options, selectIdx) in formobj.options" :key="selectIdx" :label="options.hc_main_title"
            :value="options[formobj.relation_file]" />
        </el-select>
        <!-- select选择器 -->

        <el-select v-if="formobj.select" v-model="formData[formobj.prop]" size="small" :placeholder="formobj.placeholder"
          @change="selectChange($event, index, formobj.prop)">
          <el-option v-for="(options, selectIdx) in formobj.options" :key="selectIdx" :label="options.label"
            :value="options.label" />
        </el-select>
        <!-- select多选 选择器 -->
        <el-select v-if="formobj.multiSelect" v-model="formData[formobj.prop]" size="small" multiple
          :placeholder="formobj.placeholder" @change="selectChange($event, index, formobj.prop)">
          <el-option v-for="(options, selectIdx) in formobj.options" :key="selectIdx" :label="options.label"
            :value="options.label + ''" />
        </el-select>
        <!-- 日期选择器 -->
        <el-date-picker v-if="formobj.date" v-model="formData[formobj.prop]" value-format="yyyy-MM-dd" type="date"
          size="small" :placeholder="formobj.placeholder" />
        <!-- 时间选择器 -->
        <el-time-picker v-if="formobj.time" v-model="formData[formobj.prop]" value-format="HH:mm:ss" format="HH:mm:ss"
          size="small" :placeholder="formobj.placeholder" />
        <!-- 日期时间选择器 -->
        <el-date-picker v-if="formobj.datetime" v-model="formData[formobj.prop]" value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime" size="small" :placeholder="formobj.placeholder" />
        <!-- 年月日时分秒，开始和结束时间 -->
        <el-date-picker v-if="formobj.dateTimeRange" v-model="formData[formobj.prop]" value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss" size="small" type="datetimerange" :range-separator="$t('至')"
          :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" @change="chooseTime($event, formobj.prop)" />

        <!-- 时分秒选择器，开始和结束时间 -->
        <!-- <el-time-picker
          v-if="formobj.timePickerIsRange"
          v-model="formData[formobj.prop]"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          is-range
          size="small"

          :range-separator="$t('至')"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
        /> -->
        <!-- 年月日选择器 -->
        <!-- <el-date-picker v-if="formobj.datePicker" v-model="formData[formobj.prop]" value-format="yyyy-MM-dd" size="small" :placeholder="formobj.placeholder" /> -->
        <!-- 年月日选择器，开始和介绍年月日 -->
        <!-- <el-date-picker v-if="formobj.datePickerIsRange" v-model="formData[formobj.prop]" value-format="yyyy-MM-dd" type="daterange" size="small"  :placeholder="formobj.placeholder" :range-separator="$t('至')" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" /> -->
        <!-- switch开关 -->
        <!-- {{ formobj.options }} -->
        <el-switch v-if="formobj.switch" v-model="formData[formobj.prop]" size="small"
          :active-value="formobj.options[0].label" :inactive-value="formobj.options[1].label"
          :active-text="formobj.options[0].label" :inactive-text="formobj.options[1].label"
          active-color="var(--huocms-com-color-primary)" inactive-color="rgba(0,0,0,0.2)"
          @change="formSwitchChange($event, index, formobj.prop)" />
        <!-- radio单选框 -->
        <el-radio-group v-if="formobj.radio" v-model="formData[formobj.prop]">
          <el-radio v-for="(options, radioIdx) in formobj.options" :key="radioIdx" :label="options.label"
            :value="options.value" />
        </el-radio-group>
        <!-- checkbox复选框 -->
        <el-checkbox-group v-if="formobj.checkbox" v-model="formData[formobj.prop]"
          @change="changeCheck($event, index, formobj.prop)">
          <el-checkbox v-for="(item, checkIds) in formobj.options" :key="checkIds" :label="item.label" />
        </el-checkbox-group>
        <!-- <Attachment
          ref="attachment"
          :dialog-show.sync="dialogShow"
          :attachment-type="attachmentType"
          @func="getData"
        /> -->

        <!-- 单个图片上传 -->
        <div v-if="formobj.image" class="upload">
          <div class="attachment_imgBox" @click="openAttList(formobj.prop, formobj)">
            <img v-if="formData[formobj.prop]" :src="formobj.IMGURL" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
          </div>
        </div>
        <!-- 图片集 -->
        <!-- 如果对象有值就回显，没有值就为空 -->
        <div v-if="formobj.multiImage" class="attachmentBtn">
          <div v-if="formData[formobj.prop]" class="multiBox">
            <draggable :list="formobj.list" @end="handleEnd(formobj.prop, formobj.list)">
              <div v-for="(item, idx) in formobj.list" :key="idx" class="multiBoxItem">
                <img :src="item.url" class="attachmentImg" />
                <el-input size="mini" v-model="item.description" :placeholder="$t('描述')"
                  @change="changeDesc(item)"></el-input>
                <i type="text" class="el-icon-circle-close" @click="delMultiImg(formobj.prop, formobj, item.id, idx)" />
              </div>
            </draggable>
          </div>
          <div class="attachment_imgBox" @click="openAttList(formobj.prop, formobj)">
            <i class="el-icon-camera" />
          </div>
        </div>
        <!-- 单视频 -->
        <div v-if="formobj.video" class="attachmentBtn">
          <span v-if="formData[formobj.prop]">{{ formobj.name }}</span>
          <div style="display: inline-block" @click="openAttList(formobj.prop, formobj)">
            <el-button v-if="formData[formobj.prop]" type="primary" size="mini" class="blue">
              {{ $t('替换附件') }}
            </el-button>
            <div v-else class="attachment_imgBox">
              <i class="el-icon-camera" />
            </div>
          </div>
        </div>
        <!-- 单文件 -->
        <div v-if="formobj.file" class="attachmentBtn">
          <span v-if="formData[formobj.prop]">{{ formobj.name }}</span>
          <div style="display: inline-block" @click="openAttList(formobj.prop, formobj)">
            <el-button v-if="formData[formobj.prop]" type="primary" size="mini" class="blue">
              {{ $t('替换附件') }}
            </el-button>
            <div v-else class="attachment_imgBox">
              <i class="el-icon-document" />
            </div>
          </div>
        </div>
        <!-- 多视频 -->
        <div v-if="formobj.multiVideo" class="attachmentBtn">
          <div v-if="formData[formobj.prop]" class="multiBox">
            <draggable :list="formobj.list" @end="handleEnd(formobj.prop, formobj.list)">
              <div v-for="(item, idx) in formobj.list" :key="idx" class="multiBoxItem">
                <!-- <img :src="item.url" class="attachmentImg"> -->
                <i type="text" class="el-icon-circle-close" @click="delMultiImg(formobj.prop, formobj, item.id, idx)" />
                <i class="el-icon-video-camera-solid" />
                <p class="fileName">{{ item.name }}</p>
              </div>
            </draggable>
          </div>

          <div class="attachment_imgBox" @click="openAttList(formobj.prop, formobj)">
            <i class="el-icon-camera" />
          </div>
        </div>
        <!-- 多文件 -->
        <div v-if="formobj.multiFile" class="attachmentBtn">
          <div v-if="formData[formobj.prop]" class="multiBox">
            <draggable :list="formobj.list" @end="handleEnd(formobj.prop, formobj.list)">
              <div v-for="(item, idx) in formobj.list" :key="idx" class="multiBoxItem">
                <!-- <img :src="item.url" class="attachmentImg"> -->
                <i type="text" class="el-icon-circle-close" @click="delMultiImg(formobj.prop, formobj, item.id, idx)" />
                <i class="el-icon-tickets" />
                <p class="fileName">{{ item.name }}</p>
              </div>
            </draggable>
          </div>
          <div class="attachment_imgBox" @click="openAttList(formobj.prop, formobj)">
            <i class="el-icon-document" />
          </div>
        </div>
        <!-- 按钮 -->
        <!-- <el-button v-if="formobj.button" size="small"  :loading="formobj.loading" :type="formobj.buttonType || 'primary'" @click="buttonClick(formobj.prop,index)">{{ formobj.placeholder }}</el-button> -->
        <!-- text展示 -->
        <!-- <span v-if="formobj.text" v-text="formData[formobj.prop]" /> -->
        <!-- 计量单位 -->
        <!-- <span v-if="formobj.unit" class="left10">{{ formobj.unit }}</span> -->
        <!-- 给富文本新增图片 -->
        <div v-if="formobj.richText" :ref="formobj.prop">
          <div>
            <MyTinymce ref="myTinymce" :prop="formobj.prop" :tinymce-html="content" @onClick="input(formobj.prop)" />
          </div>
        </div>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import attachmentApi from '@/api/system/attachment'
import draggable from 'vuedraggable'
export default {
  components: {
    draggable
  },
  props: {
    formObj: {
      type: Array,
      required: true
    },
    formData: {
      type: Object,
      required: true
    }
    // searchSelectOptionsCb: {
    //   type: Array
    // }
  },
  data() {
    const uploadFileUrl = this.$store.state.user.uploadFileUrl
    return {
      loading: false,
      is_one: true,
      attachmentType: '',
      attachmentTotal: '',
      infiniteScroll: false,
      attachmentLimit: 10,
      dialogShow: false,
      attachmentData: [],
      imagelist: [],
      content: '',
      text: [],
      tindata: '',
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      headers: {},
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      uploadUrl: uploadFileUrl,
      image: '',
      images: '',
      dialogImageUrl: '',
      searchSelectLoading: false,
      dialogVisible: false,
      disabled: false,
      uploadTitle: '',
      videos: [],
      text2: [],
      text3: [],
      tinType: '',
      prop: '',
      uploadType: ''
    }
  },
  watch: {},
  created() {
    // this.getAttachmentList()
  },
  methods: {
    // 拖拽完毕
    handleEnd(params, list) {
      this.formData[params] = list.map(el => el.id)
    },
    // 修改图片描述
    async changeDesc(item) {
      var res = await attachmentApi.attachmentUpdate(item)
    },
    getData(data) {
      if (data.length > 1 && this.is_one) {
        this.$message.error(this.$t('最多只能选择一张图片'))
      } else {
        if (this.uploadType == 'image') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              el.IMGURL = data[0].url
            }
          })
          this.formData[this.prop] = data[0].id
        } else if (this.uploadType == 'multiImage') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              if (this.formData[this.prop].length < 1) {
                this.formData[this.prop] = []
              }
              data.forEach(item => {
                const ids = item.id
                const obj = {
                  name: item.name,
                  url: item.url,
                  description: item.description,
                  id: item.id
                }
                this.formData[this.prop].push(ids)
                el.list.push(obj)
              })
            }
          })
        } else if (this.uploadType == 'video') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              el.IMGURL = data[0].url
              el.name = data[0].name
            }
          })
          this.formData[this.prop] = data[0].id
        } else if (this.uploadType == 'file') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              el.IMGURL = data[0].url
              el.name = data[0].name
            }
          })
          this.formData[this.prop] = data[0].id
        } else if (this.uploadType == 'multiVideo') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              if (this.formData[this.prop].length < 1) {
                this.formData[this.prop] = []
              }
              data.forEach(item => {
                const ids = item.id
                const obj = {
                  name: item.name,
                  description: item.description,
                  url: item.url,
                  id: item.id
                }
                this.formData[this.prop].push(ids)
                el.list.push(obj)
              })
            }
          })
        } else if (this.uploadType == 'multiFile') {
          this.formObj.forEach(el => {
            if (el.prop == this.prop) {
              if (this.formData[this.prop].length < 1) {
                this.formData[this.prop] = []
              }
              data.forEach(item => {
                const ids = item.id
                const obj = {
                  name: item.name,
                  url: item.url,
                  description: item.description,
                  id: item.id
                }
                this.formData[this.prop].push(ids)
                el.list.push(obj)
              })
            }
          })
        }

        this.dialogShow = false
      }
    },
    delMultiImg(prop, formobj, id, index) {
      formobj.list.forEach(item => {
        if (id == item.id) {
          // const index = formobj.list.indexOf(item)
          formobj.list.splice(index, 1)
          this.formData[prop].splice(index, 1)
        }
      })
    },
    // 打开附件弹窗
    openAttList(val, formobj, List) {
      if (formobj.image || formobj.multiImage) {
        this.attachmentType = 2
        if (formobj.image) {
          this.uploadType = 'image'
        } else {
          this.uploadType = 'multiImage'
          this.is_one = false
        }
      } else if (formobj.multiVideo || formobj.video) {
        this.attachmentType = 3
        if (formobj.video) {
          this.uploadType = 'video'
        } else {
          this.uploadType = 'multiVideo'
          this.is_one = false
        }
      } else {
        this.attachmentType = 0
        if (formobj.file) {
          this.uploadType = 'file'
        } else {
          this.uploadType = 'multiFile'
          this.is_one = false
        }
      }
      this.dialogShow = true
      this.prop = val
    },

    input(e) {
      this.tinType = e
    },
    //   多选框
    changeCheck($event, index, prop) {
      this.formData[prop] = $event
    },
    // 时间范围选择器
    chooseTime($event, prop) {
      this.formData[prop] = $event
    },
    // select变化调用
    selectChange($event, index, prop) {
      //   this.$emit('selectChange', value, index, prop)

      //   this.formData[prop] = $event.toString()
      this.formData[prop] = $event
    },
    // input的input事件
    inputINPUT(value, index, prop) {
      this.$emit('inputINPUT', value, index, prop)
    },
    // input的change事件
    inputChange(value, index, prop) {
      this.$emit('inputChange', value, index, prop)
    },
    // 搜索类型select搜索
    remoteMethod(query, index, prop) {
      if (query) {
        this.searchSelectLoading = true
        this.$emit('querySelectValue', query, index, prop)
        setTimeout(() => {
          this.formObj[index].options = this.searchSelectOptionsCb
          this.searchSelectLoading = false
        }, 500)
      } else {
        this.searchSelectOptios = []
      }
    },
    // switch变化
    formSwitchChange(val, index, prop) {
      this.$emit('formSwitchChange', val, index, prop)
    },
    // 按钮点击事件
    buttonClick(prop, index) {
      this.$emit('buttonClick', prop, index)
    },

    // 获取富文本框内容
    getTin(val) {
      // if (val) {
      if (this.$refs.myTinymce) {
        var rs = this.$refs.myTinymce[0].codeValue
        this.formData[this.tinType] = rs
        return rs
      }
    },
    // 设置富文本框内容
    setTin(v) {
      this.$refs.tin.setContent(v)
    },

    // 图片集上传
    changeImages(file, fileList) { },
    // 删除图片集
    // removeImages(file, fileList) {
    //
    //   const ids = []
    //   fileList.forEach(el => {
    //     // ids.push(el.response.data.id)
    //     ids.push(el.response.data.url)
    //   })

    //   this.formData.multiImages = fileList
    //   //   this.formData.multiImages.forEach(el => {
    //   //     ids.push(el.response.data.id)
    //   //   })
    //   //   this.formData.multiImages = ids
    // },
    // upload(val) {
    //
    //   this.uploadTitle = val
    // },
    // 多文件多视频
    uploadSuccess(item, response, file, fileList) {
      if (response.code == 0) {
        const ids = []
        fileList.forEach(el => {
          if (el.response) {
            ids.push(el.response.data.id)
          } else {
            ids.push(el.id)
          }
        })
        this.formData[item] = ids
      }
    },
    removeSuccess(item, response, file, fileList) {
      const ids = []
      if (file.length > 0) {
        file.forEach(el => {
          ids.push(el.response.data.id)
        })
        this.formData[item] = ids.toString()
      } else {
        this.formData[item] = ''
      }
    },
    // 文件删除
    handleRemove(file, fileList, limit, prop, index) {
      this.formObj[index].uploadObj.hideUpload = fileList.length == limit
      // 文件删除后判断当前文件列表长度是否等于限制长度。目的，当长度相等时隐藏文件上传按钮
      this.pushUpload(file, fileList, limit, prop)
    },
    // 文件预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 提交时验证表单，直接在父级调用
    submitForm() {
      let formValidate = Boolean
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          formValidate = true
        } else {
          this.$message.warning(this.$t('请把信息填写完整'))
          formValidate = false
        }
      })
      return formValidate
    },
    /* 清空表单
        逻辑：
        1 、如果要清空文件上传列表，要传入要清空的upload的字段名，假如多个upload用for循环，调用清空方法！
        2、清空upload之后，还要把upload上传框展示出来，通过字段名比对，获取到在formObj中的下标，通过下标操作对象属性，进行展示
       */
    resetForm(uploadArr) {
      this.$refs.ruleForm.resetFields()
      if (uploadArr) {
        for (let i = 0; i < uploadArr.length; i++) {
          this.$refs[uploadArr[i]][0].clearFiles()
          const index = this.formObj.findIndex(
            item => item.prop == uploadArr[i]
          )
          this.formObj[index].uploadObj.hideUpload = false
        }
      }
    },
    // 单个字段验证
    validateFieldProp(prop) {
      let formValidate = Boolean
      this.$refs.ruleForm.validateField(prop, valid => {
        if (!valid) {
          formValidate = true
        } else {
          formValidate = false
        }
      })
      return formValidate
    },
    // 对文件上传，删除进行赋值，调用form验证
    pushUpload(response, file, fileList, objbind) {
      if (fileList.length > 0) {
        // this.formData[prop] = fileList
      } else {
        // 表示没有数据,把字段置空
        // this.formData[prop] = ''
      }
      //   this.$refs.ruleForm.validateField(prop)// 调用验证form表单的文件上传
    }
    // 地图input的input事件
    // aMapInput(value, prop) {
    //   this.$refs[`aMap${prop}`][0].getSearch(value)
    // },
    // 子组件返回地图搜索值
    // cbSearch(val, prop) {
    //   this.setSearchVal = val.tips // 子组件
    //   this.searchShow = prop // 显示input输入联想
    // },
    // 选中地图值
    // selectVal(val, prop, index) {
    //   // 赋值的时候，拿到键，及formobj的下标，进行赋值
    //   this.formData[prop] = val.name // input输入框赋值
    //   this.formData.district = val.district // 传入省市区
    //   const lngLat = {
    //     lng: val.location.lng,
    //     lat: val.location.lat
    //   }
    //   this.formData[`${prop}location`] = lngLat
    //   this.searchShow = '' // 隐藏input输入联想
    // }
  }
}
</script>

<style lang="scss">
.el-upload--picture-card {
  width: 128px;
}
</style>
<style lang="scss" scoped>
.flexForm {
  .form-item {
    width: 50%;

    .el-form-item {
      width: calc(100% - 80px);
    }
  }
}

.attachment_imgBox {
  .el-icon-document {
    line-height: 100px;
    font-size: 20px;
    color: rgba(0, 0, 0, 0.3);
  }
}

.multiBox {
  margin-right: 5px;

  .multiBoxItem {
    width: 100px;
    height: 100px;
    text-align: center;
    cursor: pointer;
    border: dotted 1px rgba($color: #000000, $alpha: 0.1);
    background-color: rgba(0, 0, 0, 0.02);
    display: inline-block;
    margin-right: 15px;
    position: relative;
    line-height: normal;

    .fileName {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .el-icon-video-camera-solid,
    .el-icon-tickets {
      line-height: 78px;
      font-size: 20px;
      color: rgba(0, 0, 0, 0.3);
    }

    .attachmentImg {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }

    .el-input {
      line-height: 20px;
    }

    .el-icon-circle-close {
      position: absolute;
      top: -10px;
      right: -12px;
      font-size: 20px;
      color: #bbb;
      background-color: #fff;
      border-radius: 50%;
      padding: 0;
      border: none;
    }

    .el-icon-circle-close:hover {
      color: var(--huocms-com-color-primary);
    }
  }
}

.upload {
  line-height: 20px;
}

.el-textarea {
  width: 400px;
}

.el-upload--picture-card {
  width: 128px;
  height: 128px;
}

.avatar-uploader {
  .avatar {
    width: 128px;
  }
}

// .hide {
// 	/deep/ .el-upload--picture-card {
// 		display: none;
// 	}
// }
.amap_div {
  overflow: hidden;
  height: 400px;
  width: 600px;
  position: relative;

  .sreach_ul {
    position: absolute;
    top: 1;
    background-color: white;
    z-index: 9;
    min-width: 210px;
    float: auto;
    height: 200px;
    overflow: auto;
    padding: 0 20px;
    line-height: 24px;
  }
}
</style>
